package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.AccidentAudit;
import cn.wolfcode.crm.domain.Claim;
import cn.wolfcode.crm.domain.Damage;
import cn.wolfcode.crm.mapper.AccidentAuditMapper;
import cn.wolfcode.crm.mapper.DamageMapper;
import cn.wolfcode.crm.query.AccidentAuditQueryObject;
import cn.wolfcode.crm.service.IAccidentAuditService;
import cn.wolfcode.crm.util.LogicException;
import cn.wolfcode.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class AccidentAuditServiceImpl implements IAccidentAuditService {

    @Autowired
    private AccidentAuditMapper accidentAuditMapper;
    @Autowired
    private DamageMapper damageMapper;

    public void deleteByPrimaryKey(Long id) {
        accidentAuditMapper.deleteByPrimaryKey(id);
    }

    public void insert(AccidentAudit record) {
        accidentAuditMapper.insert(record);
    }

    public AccidentAudit selectByPrimaryKey(Long id) {
        return accidentAuditMapper.selectByPrimaryKey(id);
    }

    public List<AccidentAudit> selectAll() {
        return accidentAuditMapper.selectAll();
    }

    public void updateByPrimaryKey(AccidentAudit record) {
        accidentAuditMapper.updateByPrimaryKey(record);
    }

    public PageResult query(AccidentAuditQueryObject qo) {
        int count = accidentAuditMapper.query4Count(qo);
        if (count > 0) {
            return new PageResult(count, accidentAuditMapper.query4List(qo));
        }
        return new PageResult(count, Collections.EMPTY_LIST);
    }

    public void changeState(Long id) {
        AccidentAudit accidentAudit1 = accidentAuditMapper.selectclaimItemState4AaId(id);
        if (accidentAudit1.getClaimitem().getState() == false){
            throw new LogicException("请先处理理赔单明细");
        }
        AccidentAudit accidentAudit = accidentAuditMapper.selectByPrimaryKey(id);
        if (accidentAudit.getState() != null && accidentAudit.getState() != false){
            throw new LogicException("数据已审核,无法再次审核");
        }
        accidentAuditMapper.changeState(id);

        int duty = accidentAuditMapper.selectDutyByAaId(id);
        if (duty == 1){
            Long claimId = accidentAuditMapper.selectClaimIdByAaId(id);
            Damage damage = new Damage();
            Claim claim = new Claim();
            claim.setId(claimId);
            damage.setClaim(claim);
            damage.setState(false);
            damageMapper.insert(damage);
        }
    }

    public void updateByAudit(AccidentAudit accidentAudit) {
        accidentAuditMapper.updateByAudit(accidentAudit);
    }

    public Damage getDamageItemByClaimId(String staging) {
        return damageMapper.getDamageItemByClaimId(staging);
    }
}
